//
//  UserAcconut.swift
//  VVbo
//
//  Created by Mr.Run on 2017/8/25.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import UIKit

private let accountFile:NSString = "useraccount.json"


class UserAcconut: NSObject {
    var access_token: String? //= "2.00piw1VCLlbpYB34c0a5945d0AxCSb"
    var uid:String?
    var expires_in:TimeInterval = 0 {
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    var expiresDate:Date?
    override var description: String{
        return yy_modelDescription()
    }
    
    var screen_name: String?
    var avatar_large: String?
    
    override init() {
        super.init()
        guard let path = accountFile.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : Any]
        else {
            return
        }
        
        yy_modelSet(with: dict ?? [:])
//        print(self)
        
        if expiresDate?.compare(Date()) != .orderedDescending {
//            print("账户过期")
            access_token = nil
            uid = nil
            _ = try? FileManager.default.removeItem(atPath: path)
        }
        
    }
    
    func saveAccount() {
        var dict = (self.yy_modelToJSONObject() as? [String : Any]) ?? [:]
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accountFile.cz_appendDocumentDir()
         else {
            return
        }
        (data as NSData).write(toFile: filePath, atomically: true)
    }
}
